package symbol

import (
	"crypto/md5"
	"fmt"
	"src/gcommon"
	"src/zeus/logger"
)

var LoginSalt = "cac3c74dcc7dbcab221eaf75f0ba7b40" //服务器启动后会修改,用于区分不同环境的

// GenSig 生成签名
func GenSig(timestamp int64) string {
	h := md5.New()
	str := fmt.Sprintf("%s%d", gcommon.MSDKKey, timestamp)
	h.Write([]byte(str))
	return fmt.Sprintf("%x", h.Sum(nil))
}

// CreateSig 根据uid和时间戳生成一个签名
func CreateSig(uid uint64, ts int64, channel string, isadult bool) (accessToken string) {
	h := md5.New()
	str := fmt.Sprintf("%d|%d|%s|%s|%t", uid, ts, channel, LoginSalt, isadult)
	h.Write([]byte(str))
	defer func() {
		logger.Debugf(logger.LogKey_LoginFlow, "Create AccessToken=%v SourceStr=%v", accessToken, str)
	}()
	return fmt.Sprintf("%x", h.Sum(nil))
}

// CheckSig 校验客户端发送的信息
func CheckSig(token, uid, ts, channel string, isadult bool) bool {
	h := md5.New()
	str := fmt.Sprintf("%s|%s|%s|%s|%t", uid, ts, channel, LoginSalt, isadult)
	logger.Debug(logger.LogKey_LoginFlow, "Check AccessToken SourceStr: ", str)
	h.Write([]byte(str))
	s_token := fmt.Sprintf("%x", h.Sum(nil))
	if s_token != token {
		logger.Warn("CheckSig fail, s_token ", s_token, " c_token ", token)
		return false
	}
	logger.Debug(logger.LogKey_LoginFlow, "CheckSigWW c_token ", token)
	return true
}
